<template>
  <div class="chat-container">
    <!-- 头部 -->
    <div class="chat-header">
      <h1>LTCode AI Chat</h1>
      <p>智能对话助手</p>
    </div>

    <!-- 消息区域 -->
    <div class="chat-messages" ref="messagesContainer">
      <div 
        v-for="(message, index) in messages" 
        :key="index" 
        :class="['message-item', message.type]"
      >
        <div class="message-content">
          <div v-if="message.type === 'user' && message.file" class="file-info">
            <i class="el-icon-picture"></i>
            {{ message.file.name }}
          </div>
          <!-- 添加图片预览 -->
          <div v-if="message.type === 'user' && message.imageUrl" class="image-preview">
            <img :src="message.imageUrl" alt="上传的图片" class="preview-image" />
          </div>
          <div v-html="formatMessage(message.content)"></div>
          <div v-if="message.loading" class="loading">
            <i class="el-icon-loading"></i> 正在思考...
          </div>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="chat-input-area">
      <!-- API选择器 -->
      <div class="api-selector">
        <el-select 
          v-model="selectedApi" 
          placeholder="选择API接口"
          size="small"
          @change="onApiChange"
        >
          <el-option-group label="文本聊天接口">
            <el-option
              v-for="api in textApis"
              :key="api.value"
              :label="api.label"
              :value="api.value"
            />
          </el-option-group>
          <el-option-group label="多模态接口">
            <el-option
              v-for="api in multimodalApis"
              :key="api.value"
              :label="api.label"
              :value="api.value"
            />
          </el-option-group>
        </el-select>
      </div>

      <!-- 文件上传 -->
      <div v-if="needsFile" class="file-upload">
        <el-upload
          ref="upload"
          :auto-upload="false"
          :show-file-list="true"
          :on-change="handleFileChange"
          :before-remove="handleFileRemove"
          :http-request="handleHttpRequest"
          action="#"
          accept="image/*"
          drag
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将图片拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过10MB</div>
        </el-upload>
      </div>

      <!-- 输入框和发送按钮 -->
      <div class="input-container">
        <el-input
          v-model="inputMessage"
          type="textarea"
          :rows="3"
          placeholder="请输入您的消息... (Enter发送，Shift+Enter换行)"
          @keydown.native.enter.exact="handleEnterKey"
          @keydown.native.enter.shift="handleShiftEnter"
          @keydown.native.enter.ctrl="sendMessage"
          :disabled="loading"
          ref="messageInput"
        />
        <el-button 
          type="primary" 
          @click="sendMessage"
          :loading="loading"
          :disabled="!canSend"
          size="large"
        >
          发送
        </el-button>
      </div>
    </div>
  </div>
</template>

<script>
import apiService from '@/services/apiService'

export default {
  name: 'ChatView',
  data() {
    return {
      messages: [],
      inputMessage: '',
      selectedApi: 'simple',
      loading: false,
      selectedFile: null,
      textApis: [
        { value: 'simple', label: '简单聊天' },
        { value: 'substrate', label: '底层聊天' },
        { value: 'assistant', label: 'AI助手' },
        { value: 'assistantSystem', label: '系统助手' },
        { value: 'assistantStream', label: '流式助手' }
      ],
      multimodalApis: [
        { value: 'img2text', label: '图片转文本' },
        { value: 'img2text2', label: '流式图片转文本' }
      ]
    }
  },
  computed: {
    needsFile() {
      return this.multimodalApis.some(api => api.value === this.selectedApi)
    },
    canSend() {
      const hasMessage = this.inputMessage.trim().length > 0
      const hasFileWhenNeeded = !this.needsFile || this.selectedFile
      return hasMessage && hasFileWhenNeeded && !this.loading
    }
  },
  methods: {
    onApiChange() {
      this.selectedFile = null
      if (this.$refs.upload) {
        this.$refs.upload.clearFiles()
      }
    },
    handleFileChange(file) {
      this.selectedFile = file.raw
    },
    handleFileRemove() {
      this.selectedFile = null
      return true
    },
    // 添加http-request处理函数，避免el-upload的默认上传行为
    handleHttpRequest() {
      // 空实现，因为我们使用手动上传
      return true
    },
    handleEnterKey(event) {
      console.log('Enter键被按下')
      // 阻止默认的换行行为
      event.preventDefault()
      event.stopPropagation()
      // 发送消息
      this.sendMessage()
    },
    handleShiftEnter() {
      console.log('Shift+Enter键被按下')
      // 允许Shift+Enter换行，不阻止默认行为
      // 这里不需要做任何事情，让默认行为发生
    },
    async sendMessage() {
      if (!this.canSend) return

      // 创建用户消息对象
      const userMessage = {
        type: 'user',
        content: this.inputMessage,
        file: this.selectedFile,
        timestamp: new Date()
      }

      // 如果有文件，添加图片预览
      if (this.selectedFile) {
        userMessage.imageUrl = URL.createObjectURL(this.selectedFile)
      }

      this.messages.push(userMessage)

      const assistantMessage = {
        type: 'assistant',
        content: '',
        loading: true,
        timestamp: new Date()
      }
      this.messages.push(assistantMessage)

      this.loading = true
      this.scrollToBottom()

      const currentMessage = this.inputMessage
      const currentFile = this.selectedFile

      // 清空输入
      this.inputMessage = ''
      this.selectedFile = null
      if (this.$refs.upload) {
        this.$refs.upload.clearFiles()
      }

      try {
        // 特殊处理流式接口
        if (this.selectedApi === 'assistantStream') {
          await this.handleStreamResponse(assistantMessage, currentMessage)
        } else {
          const response = await apiService.sendMessage(
            this.selectedApi,
            currentMessage,
            currentFile
          )
          assistantMessage.loading = false
          assistantMessage.content = response
        }
      } catch (error) {
        assistantMessage.loading = false
        assistantMessage.content = `错误: ${error.message}`
        this.$message.error('发送消息失败')
      } finally {
        this.loading = false
        this.scrollToBottom()
      }
    },
    async handleStreamResponse(assistantMessage, message) {
      try {
        // 使用EventSource处理流式响应，实时更新界面
        return new Promise((resolve, reject) => {
          let hasData = false;
          
          const eventSource = new EventSource(`http://localhost:8001/chat/assistantStream/demo/${encodeURIComponent(message)}`);
          
          eventSource.onopen = () => {
            console.log('SSE连接已建立');
          };
          
          eventSource.onmessage = (event) => {
            console.log('收到SSE数据:', event.data);
            hasData = true;
            if (event.data && event.data !== '[DONE]') {
              assistantMessage.content += event.data;
              this.scrollToBottom();
            }
          };
          
          eventSource.onerror = (error) => {
            console.error('SSE连接错误:', error);
            eventSource.close();
            
            // 如果已经有数据，认为是正常结束
            if (hasData) {
              assistantMessage.loading = false;
              resolve();
            } else {
              assistantMessage.loading = false;
              assistantMessage.content = '流式响应错误: 连接失败';
              reject(new Error('流式连接失败，请检查后端服务是否正常运行'));
            }
          };
          
          // 监听连接关闭
          eventSource.addEventListener('close', () => {
            console.log('SSE连接关闭');
            eventSource.close();
            assistantMessage.loading = false;
            resolve();
          });
          
          // 设置超时
          // const timeout = setTimeout(() => {
          //   console.log('SSE连接超时');
          //   eventSource.close();
          //   assistantMessage.loading = false;
          //   if (!hasData) {
          //     assistantMessage.content = '流式响应错误: 请求超时';
          //   }
          //   resolve();
          // }, 300000); // 5分钟超时
        });
      } catch (error) {
        assistantMessage.loading = false;
        assistantMessage.content = `流式响应错误: ${error.message}`;
        throw error;
      }
    },
    formatMessage(content) {
      return content.replace(/\n/g, '<br>')
    },
    scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$refs.messagesContainer
        container.scrollTop = container.scrollHeight
      })
    }
  },
  mounted() {
    // 添加欢迎消息
    this.messages.push({
      type: 'assistant',
      content: '您好！我是LTCode AI助手，请选择合适的接口开始对话。',
      timestamp: new Date()
    })
  }
}
</script>

<style scoped>
.loading {
  margin-top: 8px;
  color: #999;
  font-size: 12px;
}

.file-info {
  margin-bottom: 8px;
  padding: 8px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 8px;
  font-size: 12px;
}

.file-info i {
  margin-right: 5px;
}

/* 添加图片预览样式 */
.image-preview {
  margin-bottom: 10px;
  max-width: 300px;
}

.preview-image {
  max-width: 100%;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
</style>
